package com.xb.p21_handlerpost;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView textView=null;
    Handler handler=new Handler();

    //Toast线程
    Runnable runnableToast = new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this,"Toast内容",Toast.LENGTH_LONG).show();
        }
    };

    int Count=0;
    //开启一个计数器
    Runnable runnableCount=new Runnable() {
        @Override
        public void run() {
            textView.setText("计数："+String.valueOf(Count++));
            handler.postDelayed(runnableCount, 1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_toast_post).setOnClickListener(this);
        findViewById(R.id.btn_start).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);

        textView=findViewById(R.id.tv_count);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){

            case R.id.btn_toast_post: //点击后，延迟5秒显示
                //SystemClock.uptimeMillis()程序执行到当前的时间
                handler.postAtTime(runnableToast, SystemClock.uptimeMillis()+5*1000);
                break;
            case R.id.btn_start:
                handler.postDelayed(runnableCount, 1000);
                break;
            case R.id.btn_stop:
                handler.removeCallbacks(runnableCount);
                break;
        }
    }
}